package com.botao.cms.controller;

import com.botao.cms.CMSApplication;
import com.botao.cms.utils.AjaxResult;
import com.botao.cms.utils.RequestUtils;
import com.botao.cms.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.stream.Collectors;

@Slf4j
@Controller
public class DrawingBedController {

    @GetMapping(path = {"admin/office/drawBed"})
    public String adviceListPage() {
        return "admin/office/draw_bed";
    }

    @ResponseBody
    @PostMapping("/admin/office/drawingBed/upload")
    public AjaxResult upload(MultipartFile image) {
        if (image.isEmpty()) {
            return AjaxResult.error("上传失败，请选择文件");
        }
        String originalFilename = image.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("文件后缀:{}", suffix);
        boolean flag = false;
        String[] suffixs = {".jpg", ".png", ".gif", "jpeg"};
        for (int i = 0; i < suffixs.length; i++) {
            if (suffix.equals(suffixs[i])) {
                flag = true;
                break;
            }
        }
        if(!flag){
            log.info("拦截危险文件上传");
            return AjaxResult.error("只能上传"+ Arrays.toString(suffixs) +"的文件");
        }

        String fileName = UUIDUtil.getuuid() + suffix;
        HttpServletRequest request = RequestUtils.getRequest();
        //上下问地址
        String contextPath = request.getContextPath();
        //upload目录
        String filePath = new ApplicationHome(CMSApplication.class).getDir().getPath() + "/upload/";
        log.info("upload绝对目录{}", filePath);
        //文件
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            boolean mkdirs = dest.getParentFile().mkdirs();
            log.info("文件上传目录不存在，创建目录，结果：" + mkdirs);
        }
        try {
            image.transferTo(dest);
            String webDir = contextPath + "/upload/" + fileName;
            log.info("上传成功{}", webDir);
            return AjaxResult.success(webDir);
        } catch (IOException e) {
            log.error("上传失败{}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }
}
